const app = getApp();

Page({
  data: {
    openid: '',
    form: {
      username: '',
      phone: '',
      avatar: '/assets/images/default-avatar.png'
    },
    loading: false
  },

  onLoad(options) {
    console.log('注册页面参数：', options);
    if (options.openid) {
      const nickname = options.nickname ? decodeURIComponent(options.nickname) : '';
      const avatar = options.avatar ? decodeURIComponent(options.avatar) : '/assets/images/default-avatar.png';
      
      console.log('解码后的信息：', { nickname, avatar });
      
      this.setData({
        openid: options.openid,
        form: {
          username: nickname,
          phone: '',
          avatar: avatar
        }
      });
    } else {
      wx.showToast({
        title: '缺少必要参数',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 选择头像
  async onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    console.log('选择的头像：', avatarUrl);

    try {
      // 显示加载提示
      wx.showLoading({
        title: '上传中...',
        mask: true
      });

      // 将临时文件转为 base64
      const fileContent = await new Promise((resolve, reject) => {
        wx.getFileSystemManager().readFile({
          filePath: avatarUrl,
          encoding: 'base64',
          success: res => resolve(res.data),
          fail: err => reject(err)
        });
      });

      // 调用后端上传接口
      const res = await app.request({
        url: '/user/upload_avatar/',
        method: 'POST',
        data: {
          avatar: fileContent,
          file_name: `avatar_${Date.now()}.jpg`
        }
      });

      if (res.code === 200 && res.data.url) {
        this.setData({
          'form.avatar': app.globalData.baseUrl.replace('/api', '') + res.data.url
        });
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        });
      } else {
        throw new Error(res.message || '上传失败');
      }
    } catch (error) {
      console.error('上传头像失败：', error);
      wx.showToast({
        title: '上传头像失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 输入框事件处理
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`form.${field}`]: e.detail.value
    });
  },

  // 验证表单
  validateForm() {
    const { phone } = this.data.form;

    if (!phone.trim()) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return false;
    }

    // 手机号格式验证
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 提交注册
  async handleSubmit() {
    if (this.data.loading) return;
    
    if (!this.validateForm()) return;

    this.setData({ loading: true });

    try {
      const res = await app.request({
        url: '/user/register/',
        method: 'POST',
        data: {
          ...this.data.form,
          openid: this.data.openid
        }
      });

      if (res.code === 200) {
        // 保存登录信息
        wx.setStorageSync('token', res.data.token);
        wx.setStorageSync('userInfo', res.data.user);

        wx.showToast({
          title: '注册成功',
          icon: 'success'
        });

        // 返回首页
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
      } else {
        wx.showToast({
          title: res.message || '注册失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('注册失败：', error);
      wx.showToast({
        title: error.message || '注册失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  }
}); 